"""
@Filename: tools/operate_yaml
@Author: yoko
@Time: 2023/3/27 18:48
@Describe: ...
"""
import re
from pathlib import Path

import jsonpath
import yaml
# 读yaml文件
from core.ddt_util import ddt


def read_yaml(yaml_path):
    path=Path(yaml_path)
    with open(path.absolute(),encoding="utf-8") as f:
        values=yaml.safe_load(f)
        if len(values)==1:
            for value in values:
                if "parametrizes" in value.keys():
                    new_value=ddt(value)
                    return new_value

        return values

#根据key，读取yaml文件中key对应的表达式
def extract_expression(res,case_info):
    """
        用于提取yaml文件中的提取变量的表达式
    :param yaml_path:
    :param key:
    :return:
    """

    key_value=case_info["extract"]
    print(key_value)
    for key,value in key_value.items():
        print(key,value)
        if "$" in value:
            """Jsonpath提取"""
            if res.status_code==200:
                """为例兼容parametrizes关键字带来的后果，不管接口是否返回了我们想要提取的值，都进行JsonPath提取"""
                values = jsonpath.jsonpath(res.json(), value)[0]
                write_yaml('temp/temporary_variable.yaml', key, values)
        elif "(.*?)" in value:
            """正则提取"""
            if res.status_code == 200:
                """为例兼容parametrizes关键字带来的后果，不管接口是否返回了我们想要提取的值，都进行正则提取"""
                values=re.search(value, res.text)[1]
                write_yaml('temp/temporary_variable.yaml', key, values)


# 写yaml文件
def write_yaml(yaml_path,var_name,var_value):
    with open(yaml_path,encoding="utf-8",mode="a") as f:
        data={
            var_name:var_value
        }
        yaml.dump(data,stream=f,allow_unicode=True)
if __name__ == '__main__':
    print(read_yaml("../datas/test_Alogin_password.yaml"))
